/**
 *  创建日期: 2017年8月17日上午11:52:49
 *  @copyright (c) 2017, 82% All Rights Reserved. 
 */
package com.tt.notify.producer.test;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

import org.apache.log4j.PropertyConfigurator;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.client.producer.SendStatus;
import com.tt.notify.common.constant.MQ;
import com.tt.notify.common.constant.MQ.Tag;
import com.tt.notify.common.exception.MQException;
import com.tt.notify.producer.MQProducer;

/**
 * @author   82%
 * @date     2017年8月17日 上午11:52:49
 * @version  1.0 
 */
@SuppressWarnings({"resource", "unchecked", "rawtypes"})
public class MQBirdDogProducerMain {

	private static long currentMsgK = 1;
	private static long sleepMills = 200;//200毫秒
	
	public static void main(String[] args) {

		/**
			JarFile jf = new JarFile("F:/worklog/20150408/test/lib/test.jar");        
	          
	        JarEntry entry = jf.getJarEntry("config/db.cfg.xml");  
	        InputStream input = jf.getInputStream(entry);   
	        InputStreamReader isr = new InputStreamReader(input);  
	        BufferedReader reader = new BufferedReader(isr);   
	        String s = null;  
	        while((s=reader.readLine())!=null){  
	            System.out.println(s);  
	        }  
	        reader.close();  
		 */
		PropertyConfigurator.configure(MQBirdDogProducerMain.class.getClassLoader().getResource("log4j.properties")); 
		
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{
				"classpath*:conf/spring/spring-context-*.xml"
		});
		MQProducer producer = context.getBean(com.tt.notify.producer.MQProducer.class);

		for(;;){
			doLogic(producer);
		}
	}

	/**
	 * 定义要发送的topic和tag(这里测试1：n的关系)，其实是可以（n：n）的
	 */
	static MultiValueMap<MQ.Topic, MQ.Tag> multiValueMap = new LinkedMultiValueMap<MQ.Topic, MQ.Tag>();
	static {
			multiValueMap.put(
					MQ.Topic.TOPIC_DOG, 
					Arrays.asList(
						new MQ.Tag[]{
								MQ.Tag.TAG_DOG_WANGWANG,
								MQ.Tag.TAG_DOG_XIAOHEI,
								MQ.Tag.TAG_DOG_BAIMAO,
						}
					));
			multiValueMap.put(
				MQ.Topic.TOPIC_BIRD, 
				Arrays.asList(
					new MQ.Tag[]{
							MQ.Tag.TAG_BIRD_HAWK,
							MQ.Tag.TAG_BIRD_HERON,
							MQ.Tag.TAG_BIRD_VULTURE,
							MQ.Tag.TAG_BIRD_BALD_EAGLE
					}
				));
	}
	
	
	/**
	 * 发消息逻辑
	 * @param producer
	 */
	protected static void doLogic(MQProducer producer) {
		Long batchNo = 0L;
		do{
			try {
				System.err.print("请输入本次要发送多少条消息:");
				Scanner scanner = new Scanner(System.in);
				String str = scanner.nextLine();
				batchNo = Long.valueOf(str);
			} catch (NumberFormatException e1) {
				System.err.println("输入有误！！");
			}
			
			try {
				System.err.print("请输入隔多少毫秒发送下一条消息:");
				Scanner scanner = new Scanner(System.in);
				String str = scanner.nextLine();
				sleepMills = Long.valueOf(str);
			} catch (NumberFormatException e1) {
				System.err.println("输入有误！！");
			}
			
		}while(batchNo == 0);
		
		List<MQ.Topic> topicList = new ArrayList(multiValueMap.keySet());
		int topicLen = multiValueMap.size();
		
		try {
			long total = currentMsgK + batchNo;
			int birdCount = 0;
			int dogCount = 0;
			
			for(long k = currentMsgK; k < total; k++){
				try {
					Thread.sleep(sleepMills);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				long r1 = new java.util.Random().nextLong();
				long r2 = new java.util.Random().nextLong();
				int topicIndex = (int)(Math.abs((k + r1)) % topicLen);
				
				MQ.Topic topic = topicList.get(topicIndex);
				//MQ.Topic topic = topicList.get(0);
				//MQ.Topic topic = topicList.get(1);
				
				List<Tag> tagList = multiValueMap.get(topic);
				int tagLen = tagList.size();
				int tagIndex = (int)(Math.abs((k + r2)) % tagLen);
				//System.out.println("tagIndex:" + tagIndex + ",tagLen:" + tagLen);
				MQ.Tag tag = tagList.get(tagIndex);
				
				sendMessage(producer, topic, tag, k);
				currentMsgK++;
				if(topicIndex == 0){
					dogCount++;
				}else{
					birdCount++;
				}
			}
			System.err.println(String.format("\n            |- 所有消息发送完毕！[%s]只狗，[%s]只鸟\n\n", dogCount, birdCount));
		} catch (MQException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 生产者生成消息的逻辑
	 */
	protected static void sendMessage(MQProducer producer, MQ.Topic topic, MQ.Tag tag, long k) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String now = sdf.format(new java.util.Date());
		final String msg = "第[" + k + "]只[" + topic.getDesc() + "]-[" + tag.getDesc() + "]出生了,时间: " + now;
		
		SendResult result = producer.send(topic, tag, msg);
		if (result.getSendStatus() == SendStatus.SEND_OK) {
			System.err.println("消息发送成功！msg= [ " + msg + " ] topic=" + topic + ", tag=" + tag );
		}else{
			System.err.println("消息发送失败！msg= [ " + msg + " ] topic=" + topic + ", tag=" + tag + ", result=" + result);
		}
	}
}

